<?php
/**
* reference interface
*/
class ReferenceInterface
{

	public static function query($condition) {
		
		return ReferenceTrail::model()->with('reference')->findAllByAttributes(
			$condition,
			array('order'=>'date_update desc')
		);
	}
	
	# return bool, available for borrow?
	public static function status($refid,$details=false) {
		
		$referenceTrail = new ReferenceTrail();
		
		if ($details) {
	
			$rs = $referenceTrail->with('user')->with('reference')->findByAttributes(
				array('reference_id'=>$refid),
				array('order'=>'t.date_create desc','limit'=>1));
			
			if (!( $rs === null  || $rs->date_update !== null)) {
				return array(
					'result'		=>false,
					'user_id'		=>$rs->user->id,
					'user_name'		=>$rs->user->name,
					'date_borrow'	=>$rs->date_create,
					'ref_id'		=>$rs->reference->id,
					'ref_name'		=>$rs->reference->name,
				);
			}
			return array('result'=>true);
			
		} else {

			$rs = $referenceTrail->findByAttributes(array('reference_id'=>$refid),array('order'=>'date_create desc','limit'=>1));
			return ( $rs === null  || $rs->date_update !== null);
		}
	}
	
	public static function create($refid,$userid) {
		
		if ( self::status($refid) ) {
			
			$referenceTrail = new ReferenceTrail('create');
			$referenceTrail->attributes = array(
				'reference_id'	=>$refid,
				'user_id'		=>$userid,
				'date_create'	=>date('Y-m-d H:i:s'),
			);
			$referenceTrail->save();
			#Yii::app()->db->createCommand()
			#	->update('reference',array(
			#			'reference_status_id'=>'0',
			#		),'id=:id',array(':id'=>$refid)
			#	);
			Reference::model()->updateByPk($refid,array(
				'reference_status_id'=>'0',
			));
			
			# successfully borrow, success
			return true;
		} else {
			# borrowed by other, failed
			return false;
		}
	}
	
	public static function update($refid,$userid) {
		
		if ( !self::status($refid) ) {
			
			ReferenceTrail::model()->updateAll(array(
				'date_update'=>date('Y-m-d H:i:s')
			),array(
				'condition'=>'reference_id='.$refid.' AND user_id='.$userid.'',
				'order'=>'date_create desc',
				'limit'=>1,
			));
			#Yii::app()->db->createCommand()
			#	->update('reference',array(
			#			'reference_status_id'=>'1',
			#		),'id=:id',array(':id'=>$refid)
			#	);
			Reference::model()->updateByPk($refid,array(
				'reference_status_id'=>'1',
			));
			return true;
		} else {
			return false;
		}
	}
}

?>